/**
 * 使用统计分析页面
 * 
 * 功能特性：
 * - 系统使用情况统计和分析
 * - 智能体使用统计
 * - 对话记录分析
 * - MCP工具使用统计
 * - 图表数据可视化
 * 
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

// React核心库导入
import React, { useState, useEffect } from 'react';
// React Router路由相关导入
import { useNavigate } from 'react-router-dom';
// Ant Design组件库导入
import {
  Card,
  Row,
  Col,
  Statistic,
  Table,
  DatePicker,
  Select,
  Space,
  Button,
  Tag,
  Progress,
  Typography,
  Tooltip,
  message
} from 'antd';
// Ant Design图标库导入
import {
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  DownloadOutlined,
  ReloadOutlined,
  RobotOutlined,
  MessageOutlined
} from '@ant-design/icons';
// 日期处理库导入
import dayjs from 'dayjs';
// 相对时间插件导入
import relativeTime from 'dayjs/plugin/relativeTime';

// 启用相对时间插件
dayjs.extend(relativeTime);

// 解构Ant Design组件
const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

// 统计数据接口
interface UsageStats {
  totalAgents: number;
  activeAgents: number;
  totalConversations: number;
  activeConversations: number;
  totalMessages: number;
  totalMcpTools: number;
  activeMcpServers: number;
  averageResponseTime: number;
  successRate: number;
  errorRate: number;
  timestamp: string;
}

// 智能体使用统计接口
interface AgentUsageStats {
  agentId: string;
  agentName: string;
  usageCount: number;
  successCount: number;
  errorCount: number;
  averageResponseTime: number;
  lastUsedAt: string;
}

// 工具使用统计接口
interface ToolUsageStats {
  toolName: string;
  toolCategory: string;
  usageCount: number;
  successCount: number;
  errorCount: number;
  averageExecutionTime: number;
}

// 时间范围选项
const timeRangeOptions = [
  { label: '今天', value: 'today' },
  { label: '最近7天', value: 'last7days' },
  { label: '最近30天', value: 'last30days' },
  { label: '本月', value: 'thisMonth' },
  { label: '上月', value: 'lastMonth' },
  { label: '自定义', value: 'custom' }
];

/**
 * 使用统计分析页面组件
 */
const UsageStatsList: React.FC = () => {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState<UsageStats | null>(null);
  const [agentStats, setAgentStats] = useState<AgentUsageStats[]>([]);
  const [toolStats, setToolStats] = useState<ToolUsageStats[]>([]);
  const [timeRange, setTimeRange] = useState('last7days');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(7, 'day'),
    dayjs()
  ]);

  // 路由导航
  const navigate = useNavigate();

  // 加载统计数据
  const loadStats = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 模拟统计数据
      const mockStats: UsageStats = {
        totalAgents: 12,
        activeAgents: 8,
        totalConversations: 156,
        activeConversations: 23,
        totalMessages: 2847,
        totalMcpTools: 45,
        activeMcpServers: 6,
        averageResponseTime: 1250,
        successRate: 95.8,
        errorRate: 4.2,
        timestamp: new Date().toISOString()
      };

      const mockAgentStats: AgentUsageStats[] = [
        {
          agentId: '1',
          agentName: '客服助手',
          usageCount: 856,
          successCount: 823,
          errorCount: 33,
          averageResponseTime: 980,
          lastUsedAt: new Date().toISOString()
        },
        {
          agentId: '2',
          agentName: '代码助手',
          usageCount: 642,
          successCount: 615,
          errorCount: 27,
          averageResponseTime: 1450,
          lastUsedAt: new Date(Date.now() - 1000 * 60 * 30).toISOString()
        },
        {
          agentId: '3',
          agentName: '文档助手',
          usageCount: 423,
          successCount: 401,
          errorCount: 22,
          averageResponseTime: 1120,
          lastUsedAt: new Date(Date.now() - 1000 * 60 * 60).toISOString()
        }
      ];

      const mockToolStats: ToolUsageStats[] = [
        {
          toolName: 'web_search',
          toolCategory: '搜索',
          usageCount: 1256,
          successCount: 1189,
          errorCount: 67,
          averageExecutionTime: 850
        },
        {
          toolName: 'file_read',
          toolCategory: '文件',
          usageCount: 892,
          successCount: 875,
          errorCount: 17,
          averageExecutionTime: 320
        },
        {
          toolName: 'database_query',
          toolCategory: '数据库',
          usageCount: 567,
          successCount: 534,
          errorCount: 33,
          averageExecutionTime: 1250
        },
        {
          toolName: 'calculator',
          toolCategory: '计算',
          usageCount: 445,
          successCount: 445,
          errorCount: 0,
          averageExecutionTime: 150
        }
      ];

      setStats(mockStats);
      setAgentStats(mockAgentStats);
      setToolStats(mockToolStats);
    } catch (error) {
      message.error('加载统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理时间范围变化
  const handleTimeRangeChange = (value: string) => {
    setTimeRange(value);
    
    let startDate: dayjs.Dayjs;
    let endDate = dayjs();
    
    switch (value) {
      case 'today':
        startDate = dayjs().startOf('day');
        break;
      case 'last7days':
        startDate = dayjs().subtract(7, 'day');
        break;
      case 'last30days':
        startDate = dayjs().subtract(30, 'day');
        break;
      case 'thisMonth':
        startDate = dayjs().startOf('month');
        break;
      case 'lastMonth':
        startDate = dayjs().subtract(1, 'month').startOf('month');
        endDate = dayjs().subtract(1, 'month').endOf('month');
        break;
      default:
        return;
    }
    
    setDateRange([startDate, endDate]);
  };

  // 处理日期范围变化
  const handleDateRangeChange = (dates: any, dateStrings: [string, string]) => {
    if (dates && dates[0] && dates[1]) {
      setDateRange([dates[0], dates[1]]);
      setTimeRange('custom');
    }
  };

  // 导出数据
  const handleExport = (type: string) => {
    message.info(`导出${type}数据功能正在开发中`);
  };

  // 刷新数据
  const handleRefresh = () => {
    loadStats();
  };

  // 组件挂载时加载数据
  useEffect(() => {
    loadStats();
  }, [dateRange]);

  // 智能体使用统计表格列定义
  const agentColumns = [
    {
      title: '智能体名称',
      dataIndex: 'agentName',
      key: 'agentName',
      render: (text: string, record: AgentUsageStats) => (
        <Button 
          type="link" 
          onClick={() => navigate(`/agents/${record.agentId}`)}
        >
          {text}
        </Button>
      )
    },
    {
      title: '使用次数',
      dataIndex: 'usageCount',
      key: 'usageCount',
      sorter: (a: AgentUsageStats, b: AgentUsageStats) => a.usageCount - b.usageCount,
      render: (count: number) => count.toLocaleString()
    },
    {
      title: '成功率',
      key: 'successRate',
      render: (record: AgentUsageStats) => {
        const rate = (record.successCount / record.usageCount * 100).toFixed(1);
        return (
          <div>
            <Progress 
              percent={parseFloat(rate)} 
              size="small" 
              status={parseFloat(rate) > 90 ? 'success' : parseFloat(rate) > 80 ? 'normal' : 'exception'}
            />
            <Text type="secondary">{rate}%</Text>
          </div>
        );
      }
    },
    {
      title: '平均响应时间',
      dataIndex: 'averageResponseTime',
      key: 'averageResponseTime',
      render: (time: number) => `${time}ms`,
      sorter: (a: AgentUsageStats, b: AgentUsageStats) => a.averageResponseTime - b.averageResponseTime
    },
    {
      title: '最后使用',
      dataIndex: 'lastUsedAt',
      key: 'lastUsedAt',
      render: (time: string) => dayjs(time).fromNow(),
      sorter: (a: AgentUsageStats, b: AgentUsageStats) => new Date(a.lastUsedAt).getTime() - new Date(b.lastUsedAt).getTime()
    }
  ];

  // 工具使用统计表格列定义
  const toolColumns = [
    {
      title: '工具名称',
      dataIndex: 'toolName',
      key: 'toolName',
      render: (text: string) => <Tag color="blue">{text}</Tag>
    },
    {
      title: '类别',
      dataIndex: 'toolCategory',
      key: 'toolCategory',
      render: (category: string) => <Tag color="cyan">{category}</Tag>
    },
    {
      title: '使用次数',
      dataIndex: 'usageCount',
      key: 'usageCount',
      sorter: (a: ToolUsageStats, b: ToolUsageStats) => a.usageCount - b.usageCount,
      render: (count: number) => count.toLocaleString()
    },
    {
      title: '成功率',
      key: 'successRate',
      render: (record: ToolUsageStats) => {
        const rate = (record.successCount / record.usageCount * 100).toFixed(1);
        return (
          <div>
            <Progress 
              percent={parseFloat(rate)} 
              size="small" 
              status={parseFloat(rate) > 95 ? 'success' : parseFloat(rate) > 85 ? 'normal' : 'exception'}
            />
            <Text type="secondary">{rate}%</Text>
          </div>
        );
      }
    },
    {
      title: '平均执行时间',
      dataIndex: 'averageExecutionTime',
      key: 'averageExecutionTime',
      render: (time: number) => `${time}ms`,
      sorter: (a: ToolUsageStats, b: ToolUsageStats) => a.averageExecutionTime - b.averageExecutionTime
    }
  ];

  return (
    <div>
      {/* 页面标题和操作区域 */}
      <div style={{ marginBottom: 24 }}>
        <Row justify="space-between" align="middle">
          <Col>
            <Title level={2} style={{ margin: 0 }}>
              <BarChartOutlined /> 使用统计
            </Title>
          </Col>
          <Col>
            <Space>
              <Button 
                icon={<ReloadOutlined />} 
                onClick={handleRefresh}
                loading={loading}
              >
                刷新
              </Button>
              <Button 
                icon={<DownloadOutlined />}
                onClick={() => handleExport('CSV')}
              >
                导出CSV
              </Button>
              <Button 
                icon={<DownloadOutlined />}
                onClick={() => handleExport('PDF')}
              >
                导出PDF
              </Button>
            </Space>
          </Col>
        </Row>
      </div>

      {/* 时间范围选择 */}
      <Card style={{ marginBottom: 24 }}>
        <Row align="middle">
          <Col span={4}>
            <Text strong>时间范围：</Text>
          </Col>
          <Col span={6}>
            <Select
              value={timeRange}
              onChange={handleTimeRangeChange}
              style={{ width: '100%' }}
            >
              {timeRangeOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={12} offset={1}>
            {timeRange === 'custom' && (
              <RangePicker
                value={dateRange}
                onChange={handleDateRangeChange}
                style={{ width: '100%' }}
              />
            )}
          </Col>
        </Row>
      </Card>

      {/* 总体统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={8} lg={6}>
          <Card>
            <Statistic
              title="智能体总数"
              value={stats?.totalAgents || 0}
              suffix={<Tag color="blue">活跃 {stats?.activeAgents || 0}</Tag>}
              prefix={<RobotOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8} lg={6}>
          <Card>
            <Statistic
              title="对话总数"
              value={stats?.totalConversations || 0}
              suffix={<Tag color="green">进行中 {stats?.activeConversations || 0}</Tag>}
              prefix={<MessageOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8} lg={6}>
          <Card>
            <Statistic
              title="消息总数"
              value={stats?.totalMessages || 0}
              prefix={<LineChartOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={8} lg={6}>
          <Card>
            <Statistic
              title="成功率"
              value={stats?.successRate || 0}
              suffix="%"
              precision={1}
              prefix={<PieChartOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 详细统计表格 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card 
            title="智能体使用统计" 
            extra={
              <Text type="secondary">
                平均响应时间: {stats?.averageResponseTime || 0}ms
              </Text>
            }
          >
            <Table
              columns={agentColumns}
              dataSource={agentStats}
              rowKey="agentId"
              pagination={{ pageSize: 5 }}
              loading={loading}
              size="small"
            />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card 
            title="工具使用统计" 
            extra={
              <Text type="secondary">
                活跃服务器: {stats?.activeMcpServers || 0}
              </Text>
            }
          >
            <Table
              columns={toolColumns}
              dataSource={toolStats}
              rowKey="toolName"
              pagination={{ pageSize: 5 }}
              loading={loading}
              size="small"
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default UsageStatsList;